package cn.easybuy.dao.impl;

import cn.easybuy.dao.BaseDao;
import cn.easybuy.dao.NewsDAO;
import cn.easybuy.entity.News;
import cn.easybuy.entity.PageInfo;
import cn.easybuy.entity.User;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class NewsDAOImpl extends BaseDao implements NewsDAO {


    @Override
    public PageInfo<News> listPage(PageInfo<News> page) throws SQLException {
        String sql="select * from easybuy_news limit ?,?";

        Object[] obj = new Object[2];
        obj[0]=(page.getPageNo()-1)*page.getPageSize();//当前页
        obj[1]=page.getPageSize();//每页显示的条数

        ResultSet rs =executeQuery(sql,obj);
        ArrayList<News>list=new ArrayList<>();
        while (rs.next()){
            int id = rs.getInt("id");
            String title = rs.getString("title");
            String content = rs.getString("content");
            String createTime = rs.getString("createTime");

            News n = new News(id,title,content,createTime);
            //把数据添加到list集合
            list.add(n);
        }

        page.setPageList(list);

        //总记录条数 总页数
        String sqlCount="select count(*) total  from easybuy_news";
        ResultSet rs2 =executeQuery(sqlCount,null);
        int count=0;
        if (rs2.next()){
            count=rs2.getInt("total");
        }
        //计算总页数
        int size =page.getPageSize();
        //count 是总记录条数, size是每页显示的条数 num是条数
        int num=count/size==0?count/size : count/size+1;
        page.setPageNum(num);
        page.setPageCount(count);
        return page;


    }

    @Override
    public News getNewsById(int id) throws SQLException {
        String sql = "select * from easybuy_news where id =?";
        Object[] obj = new Object[1];
        obj[0]=id;
        ResultSet rs = executeQuery(sql,obj);
        while (rs.next()){
            int id1 = rs.getInt("id");
            String title = rs.getString("title");
            String content = rs.getString("content");
            String createTime = rs.getString("createTime");
            News ne = new News(id1,title,content,createTime);
            return ne;
        }
        return null;
    }
}
